<template>
  <Dialog v-model="dialogVisible" title="条件检查" width="800px">
    <div v-loading="formLoading">
      <el-form
        ref="formRef"
        :model="formData"
        label-width="120px"
      >
        <el-form-item label="检查对象">
          <el-card class="check-object">
            <div class="info-row">
              <span class="label">申请人：</span>
              <span>{{ checkInfo.candidateName }}</span>
            </div>
            <div class="info-row">
              <span class="label">身份证号：</span>
              <span>{{ checkInfo.idCard }}</span>
            </div>
            <div class="info-row">
              <span class="label">申报职业：</span>
              <span>{{ checkInfo.professionName }}</span>
            </div>
            <div class="info-row">
              <span class="label">申报等级：</span>
              <span>{{ checkInfo.skillLevel }}</span>
            </div>
          </el-card>
        </el-form-item>
        
        <el-form-item label="检查项目">
          <el-table :data="checkItems" border style="width: 100%">
            <el-table-column prop="itemName" label="检查项目" width="200" />
            <el-table-column prop="requirement" label="要求" min-width="250" />
            <el-table-column label="检查结果" width="120">
              <template #default="{ row, $index }">
                <el-select
                  v-model="row.checkResult"
                  placeholder="选择结果"
                  size="small"
                  @change="updateCheckResult($index, row.checkResult)"
                >
                  <el-option label="通过" value="通过" />
                  <el-option label="不通过" value="不通过" />
                  <el-option label="待补充" value="待补充" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="200">
              <template #default="{ row, $index }">
                <el-input
                  v-model="row.remarks"
                  placeholder="请输入备注"
                  size="small"
                  @input="updateRemarks($index, row.remarks)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        
        <el-form-item label="总体结论">
          <el-radio-group v-model="formData.overallResult">
            <el-radio label="通过">条件检查通过</el-radio>
            <el-radio label="不通过">条件检查不通过</el-radio>
            <el-radio label="待补充">需要补充材料</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="检查意见">
          <el-input
            v-model="formData.checkComments"
            type="textarea"
            :rows="4"
            placeholder="请输入检查意见"
          />
        </el-form-item>
        
        <el-form-item label="需补充材料" v-if="formData.overallResult === '待补充'">
          <el-input
            v-model="formData.supplementMaterials"
            type="textarea"
            :rows="3"
            placeholder="请详细说明需要补充的材料"
          />
        </el-form-item>
        
        <el-form-item label="补充期限" v-if="formData.overallResult === '待补充'">
          <el-date-picker
            v-model="formData.supplementDeadline"
            type="date"
            placeholder="请选择补充期限"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <div class="check-summary">
        <el-alert
          :title="getSummaryTitle()"
          :type="getSummaryType()"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>通过项目：{{ passedCount }} 项</p>
            <p>不通过项目：{{ failedCount }} 项</p>
            <p>待补充项目：{{ pendingCount }} 项</p>
          </template>
        </el-alert>
      </div>
    </div>
    
    <template #footer>
      <el-button @click="submitCheck" type="primary" :disabled="formLoading || !canSubmit">
        提交检查结果
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

defineOptions({ name: 'ConditionCheck' })

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()

const checkInfo = reactive({
  candidateId: undefined,
  candidateName: '',
  idCard: '',
  professionName: '',
  skillLevel: ''
})

const formData = reactive({
  overallResult: '',
  checkComments: '',
  supplementMaterials: '',
  supplementDeadline: null
})

const checkItems = ref([
  {
    itemName: '年龄要求',
    requirement: '18-60周岁',
    checkResult: '',
    remarks: ''
  },
  {
    itemName: '学历要求',
    requirement: '初中及以上学历',
    checkResult: '',
    remarks: ''
  },
  {
    itemName: '工作经验',
    requirement: '相关工作经验2年以上',
    checkResult: '',
    remarks: ''
  },
  {
    itemName: '身体条件',
    requirement: '身体健康，无影响工作的疾病',
    checkResult: '',
    remarks: ''
  },
  {
    itemName: '培训证明',
    requirement: '完成相关培训并取得证明',
    checkResult: '',
    remarks: ''
  }
])

const passedCount = computed(() => checkItems.value.filter(item => item.checkResult === '通过').length)
const failedCount = computed(() => checkItems.value.filter(item => item.checkResult === '不通过').length)
const pendingCount = computed(() => checkItems.value.filter(item => item.checkResult === '待补充').length)

const canSubmit = computed(() => {
  return checkItems.value.every(item => item.checkResult !== '') && formData.overallResult !== ''
})

/** 打开弹窗 */
const open = async (candidate: any) => {
  dialogVisible.value = true
  Object.assign(checkInfo, candidate)
  await loadCheckItems()
  resetForm()
}

/** 加载检查项目 */
const loadCheckItems = async () => {
  try {
    // TODO: 根据职业和等级加载对应的检查项目
    // const items = await getCheckItemsByProfession(checkInfo.professionCode, checkInfo.skillLevel)
    // checkItems.value = items
  } catch (error) {
    console.error('加载检查项目失败:', error)
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.overallResult = ''
  formData.checkComments = ''
  formData.supplementMaterials = ''
  formData.supplementDeadline = null
  
  checkItems.value.forEach(item => {
    item.checkResult = ''
    item.remarks = ''
  })
}

/** 更新检查结果 */
const updateCheckResult = (index: number, result: string) => {
  checkItems.value[index].checkResult = result
  updateOverallResult()
}

/** 更新备注 */
const updateRemarks = (index: number, remarks: string) => {
  checkItems.value[index].remarks = remarks
}

/** 自动更新总体结论 */
const updateOverallResult = () => {
  const allChecked = checkItems.value.every(item => item.checkResult !== '')
  if (!allChecked) return
  
  const hasFailed = checkItems.value.some(item => item.checkResult === '不通过')
  const hasPending = checkItems.value.some(item => item.checkResult === '待补充')
  
  if (hasFailed) {
    formData.overallResult = '不通过'
  } else if (hasPending) {
    formData.overallResult = '待补充'
  } else {
    formData.overallResult = '通过'
  }
}

/** 获取摘要标题 */
const getSummaryTitle = () => {
  if (passedCount.value === checkItems.value.length) {
    return '所有检查项目均通过'
  } else if (failedCount.value > 0) {
    return '存在不通过的检查项目'
  } else if (pendingCount.value > 0) {
    return '存在需要补充材料的检查项目'
  }
  return '检查进行中'
}

/** 获取摘要类型 */
const getSummaryType = () => {
  if (passedCount.value === checkItems.value.length) {
    return 'success'
  } else if (failedCount.value > 0) {
    return 'error'
  } else if (pendingCount.value > 0) {
    return 'warning'
  }
  return 'info'
}

/** 提交检查结果 */
const submitCheck = async () => {
  try {
    formLoading.value = true
    
    const checkData = {
      candidateId: checkInfo.candidateId,
      checkItems: checkItems.value,
      overallResult: formData.overallResult,
      checkComments: formData.checkComments,
      supplementMaterials: formData.supplementMaterials,
      supplementDeadline: formData.supplementDeadline
    }
    
    // TODO: 调用提交条件检查的API
    // await submitConditionCheck(checkData)
    
    ElMessage.success('条件检查结果提交成功')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('提交条件检查失败:', error)
    ElMessage.error('提交条件检查失败')
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped>
.check-object {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: bold;
  min-width: 80px;
  color: #606266;
}

.check-summary {
  margin-top: 20px;
}
</style>
